<template>
  <div>
    <content-box one="商品分类" two="分类列表">
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加商品</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格 -->
      <tree-table
        class="treeTable"
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        border
        :show-row-hover="false"
      >
        <template slot="isOK" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_delete !== false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level == '0'">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level == '1'"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="option" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCate(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" icon="el-icon-delete" size="mini"
            >删除</el-button
          >
        </template>
      </tree-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </content-box>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="closeAddCateDialog"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRefer"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectCatesKey"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCatChanged"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCat">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框 -->

    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="closeEidtCateDialog"
    >
      <el-form
        :model="editCateForm"
        :rules="addCateFormRules"
        ref="editCateFormRefer"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- selectCatesKey,存放id -->
          <el-cascader
            v-model="selectCatesKey"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCatChanged"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import LoginVue from "../Login.vue";
export default {
  data() {
    return {
      //添加分类的表单数据绑定对象
      addCateForm: {
        //将要添加的分类名称
        cat_name: "",
        //父级分类的id
        cat_pid: 0,
        //在不选择分类时，默认添加的是一级分类
        cat_level: 0,
      },
      //编辑的表达那数据绑定对象
      editCateForm: {},
      //添加分类表单的验证规则对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { min: 1, max: 10, message: "长度在 3到 10个字符", trigger: "blur" },
        ],
      },
      //父级分类的数据绑定对象
      parentCateList: [],

      cateForm: {},
      //查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      cateList: [],
      //总数居条数
      total: 0,
      //为table指定列定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          //表示将当前页定义为模板列
          type: "template",
          //表示当前页使用的模板名称
          template: "isOK",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "option",
        },
      ],
      //控制添加分类对话框
      addCateDialogVisible: false,
      //
      selectCatesKey: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        expandTrigger: "hover",
        multiple: false,
        checkStrictly: true,
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //编辑分类对话框的显示与隐藏
      editCateDialogVisible: false,
    };
  },
  created() {
    this.getCatesList();
  },
  methods: {
    //获取商品分类数据
    async getCatesList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      console.log(res.data);
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    //监听pagesize变化
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCatesList();
    },
    //监听pagenum变化
    handleCurrentChange(newNum) {
      this.queryInfo.pagenum = newNum;
      this.getCatesList();
    },
    showAddCateDialog() {
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    //获取父级分类的数据
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      // console.log(res.data);
      this.parentCateList = res.data;
    },
    //选择项发生变化触发这个函数
    parentCatChanged() {
      // selectCatesKey一定要是数组
      console.log(this.selectCatesKey);
      //如果 addCateForm数据中的length大于0，证明选中父级分类
      if (this.selectCatesKey.length > 0) {
        this.addCateForm.cat_pid = this.selectCatesKey.length - 1;
        this.addCateForm.cat_level = this.selectCatesKey.length;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
      // console.log(this.addCateForm.cat_level);
    },
    //点击按钮添加分类
    async addCat() {
      // console.log(this.addCateForm);
      this.$refs.addCateFormRefer.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) return this.$message.error("添加分类失败");

        this.getCatesList();
        this.$message.success("添加分类成功");
      });
    },
    //关闭添加分类对话框
    closeAddCateDialog() {
      this.$refs.addCateFormRefer.resetFields();
      this.selectCatesKey = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },
    //编辑按钮点击后执行
    async editCate(row) {
      //先获取父级分类数据
      this.getParentCateList();
      // console.log(`categories/ + ${row.cat_id}`);
      //查询对应项分类
      const { data: res } = await this.$http.get(`categories/${row.cat_id}`);
      if (res.meta.status !== 200) return this.$message.error("查询分类失败");

      console.log(this.selectCatesKey);

      this.editCateForm = res.data;
      this.$message.success("查询分类成功");
      this.editCateDialogVisible = true;
    },
    // 编辑对话框关闭
    closeEidtCateDialog() {},
  },
};
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>